package com.ckm.util;

import com.alibaba.excel.EasyExcel;
import com.ckm.exception.BusinessException;
import com.ckm.listener.ExcelListener;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelUtils {

    public static <T> List<T> readExcel(InputStream inputStream, final Class<?> clazz) {
        return EasyExcel.read(inputStream)
                .registerReadListener(new ExcelListener<>())
                .head(clazz)
                .sheet(0)
                .headRowNumber(1)
                .doReadSync();
    }

    public static boolean checkFileExt(MultipartFile file, String[] fileExt) {
        boolean checkResultError = true;
        if (file.isEmpty()) {
            throw new BusinessException(250,"文件为空");
        }
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String uploadFileExt = fileName.substring(fileName.indexOf('.') + 1);
        for (String s : fileExt) {
            if (uploadFileExt.equals(s)) {
                checkResultError = false;
                break;
            }
        }
        return checkResultError;
    }

    public static InputStream getInputStream(MultipartFile file,String[] fileExt) throws IOException {
        if (ExcelUtils.checkFileExt(file, fileExt)){
            throw new BusinessException(250,"文件格式错误");
        }
        return file.getInputStream();
    }

    public static List<List<String>> head(String[] head) {
        List<List<String>> headList = new ArrayList<>();
        for (String s : head) {
            List<String> list = new ArrayList<>();
            list.add(s);
            headList.add(list);
        }
        return headList;
    }

    public static void writeExcel(String[] head, List<List<Object>> dataList, String fileName, HttpServletResponse response){
        try {
            String encode = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;fileName=" + encode);
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream).head(head(head)).sheet(fileName).doWrite(dataList);
            IOUtils.close(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
